package com.eve.springcloud.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.eve.springcloud.common.Jsons;
import com.eve.springcloud.service.PaymentService;

@RestController
public class NacosConsumerController {
	/**
	 * 请求Nacos上的服务地址
	 */
	public static final String service_url = "http://nacos-order";
	
	@Resource
	private RestTemplate restTemplate;
	
	/**
	 * @SentinelResource 的fallback管运行异常
	 * @param id
	 * @return
	 */
	@RequestMapping("/consumer/fallback/{id}")
//	@SentinelResource(value = "fallback", fallback = "handlerFallback")  // 只配置运行异常返回
//	@SentinelResource(value = "fallback", blockHandler = "blockHandler") // 只配置限流异常返回
	@SentinelResource(value = "fallback", blockHandler = "blockHandler"
	, fallback = "handlerFallback")  // 运行异常和限流返回都配置-》都起作用，block优先fallback
	public Jsons fallback(@PathVariable Long id) {
		Jsons result = restTemplate.getForObject(service_url + "/fallback/" + id, Jsons.class, id);
		if(id == 4) {
			throw new IllegalArgumentException("非法参数异常。。。");
		}else if(result.get("data") == null){
			throw new NullPointerException("没有记录，空指针异常");
		}
		return result;
	}
	
	public Jsons blockHandler(@PathVariable Long id, BlockException e) {
		return Jsons.error(444, "block限流，exception：" + e.getMessage()).put("data", id);
	}
	
	/**
	 *  案例：异常fallback（不会报error page）
	 *  
	 * @param id
	 * @param e
	 * @return
	 */
	public Jsons handlerFallback(@PathVariable Long id, Throwable e) {
		return Jsons.error(444, "兜底异常，exception：" + e.getMessage()).put("data", id);
	}
	/////////// Feign 系列 20200708
	@Resource
	private PaymentService paymentService;
	
	@RequestMapping("/consumer/payment/{id}")
	public Jsons paymentFallback(@PathVariable Long id) {
		
		return paymentService.paymentSql(id);
	}
	
}
